package org.myrpc.client;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.myrpc.rpc.RpcRequest;
import org.myrpc.rpc.RpcResponse;
import org.myrpc.utils.CloseUtils;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

public class RpcClient {
	
	public Object start(RpcRequest request,String host,int port) throws Throwable {
		InputStream in =null;
		HessianInput hessianInput = null;
		OutputStream out =null;
		HessianOutput hessianOutput = null;
		try {
			Socket socket = new Socket(host,port);
		
			//发送请求
			out=socket.getOutputStream();
			hessianOutput = new HessianOutput(out);
			hessianOutput.writeObject(request);
			
			
			//获取响应
			in = socket.getInputStream();
			hessianInput = new HessianInput(in);
			Object result = hessianInput.readObject();
			if(!(result instanceof RpcResponse)) {
				throw new RuntimeException("服务器返回参数不正确");
			}
			RpcResponse response = (RpcResponse) result;
			//判断结果
			if(response.getError()!=null) {
				throw response.getError();
			}
			//返回结果
			return response.getResult();
		}catch (Exception e) {
			throw new RuntimeException("客户端发生异常！");
		}finally {
			CloseUtils.close(in, hessianInput, out, hessianOutput);
		}
		
		
	}

}
